<?php
namespace core;
ignore_user_abort(false);  // 关闭浏览器终止运行
set_time_limit(5);  // 脚本最大运行时间

// 自动加载
spl_autoload_register(function($class) {
    $class = strtr($class, '\\', DIRECTORY_SEPARATOR);
    require(ROOT_DIR. DIRECTORY_SEPARATOR. $class. '.php');
});

class muggle
{
    private static $api = null;

    public function init()
    {
        return new self;
    }

    private $app;

    private function __construct() {
        $this->app = null;
    }

    public function set($json)
    {
        header('Content-type: '. $json['type']. ';'. 'charset='. $json['charset']);
        return $this;
    }

    public function link($pack, $app)
    {
        $application = "\\{$pack}\\{$app}\\". API_FILE;
        $cmd = new cmd;
        if (! $cmd::check()) {
            format::res_error(-999, '对不起，您请求的包不存在~');
            exit(0);
        }
        $this->app = new $application;
        return $this;
    }

    public function send($mode)
    {
        if (empty($this->app)) {
            return false;
        }
        $application = empty($_GET['app']) ? 'app' : $_GET['app'];
        if (! method_exists($this->app, $application)) {
            format::res_error(-744, '对不起，您请求的应用不存在~');
            exit(0);
        }
        $this->systemout($this->app->$application(), $mode);
    }

    private function systemout($arr, $mode)
    {
        if ($mode == 'json') {
            echo json_encode($arr);
        }
    }
}